import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { PcontentService } from '@app/services/pcontent/pcontent.service';
import { CartService } from '@app/services/cart/cart.service';
import { SocketioService } from '@app/services/socketio/socketio.service';
import { storage } from '@app/utils';
import { tableId } from '@app/config';

@Component({
  selector: 'app-pcontent',
  templateUrl: './pcontent.component.html',
  styleUrls: ['./pcontent.component.scss']
})
export class PcontentComponent implements OnInit {
  private tableId: string = '';
  // 商品id
  private subId: string = '';
  // 商品详情
  private goodsDetail: any = {};
  // 商品数量
  private num: number = 1;
  // 限售数量
  private mostNum: number = 0;
  constructor (
    private readonly router: Router,
    private readonly route: ActivatedRoute,
    private readonly pcontentService: PcontentService,
    private readonly cartService: CartService,
    private readonly socketio: SocketioService,
  ) {
    this.tableId = storage.getItem(tableId);
  }

  ngOnInit() {
    this.route.params.subscribe((params: any) => {
      this.subId = params.id;
      if (this.subId) {
        this.initGoodsDetail(this.subId);
      }
    });
  }

  // 根据id获取商品详情
  private initGoodsDetail(id: string): void {
    this.pcontentService.goodsDetail$(id).subscribe(data => {
      const { code, message, result } = data;
      if (Object.is(code, 0)) {
        // console.log(result);
        this.mostNum = result.most_num;
        this.goodsDetail = result;
      } else {
        console.log('获取商品详情失败');
      }
    })
  }

  //减少数量
  decNum() {
    if (this.num > 1) {
      --this.num;
    }
  }
  //增加数量
  incNum() {
    if (this.num < this.mostNum) {
      ++this.num;
    }
  }

  // 加入购物车
  private addCart(): void {
    const postData = {
      tableId: this.tableId, // 桌号需要扫码获取
      goodsId: this.subId, //商品id
      num: this.num, // 商品数量
    };
    this.cartService.addCart$(postData).subscribe(data => {
      const { code, message, result } = data;
      if (Object.is(code, 0)) {
        this.socketio.socket.emit('addCart', this.tableId);
        // 成功跳转到首页
        this.router.navigate(['/home']);
      } else {
        console.log(message);
      }
    })
  }
}
